package com.shanghaionstar.nav.presenter;

import android.content.Intent;
import android.content.res.Resources;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.map.common.MapException;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.iview.INavChoosePointInMapView;
import com.shanghaionstar.nav.model.LocateStatus;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.SetAddressResult;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.NavHolder;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by 6335yz on 2016/7/18.
 */
public class NavChoosePointInMapPresenter extends BasePresenter implements MapHandler.OnCustomCoderGpsListener {

    private AbstractMapActivity mapActivity;
    private Resources res;
    private INavChoosePointInMapView navChoosePointInMapView;
    private Subscription locateSubscription;
    private Subscription vehicleSubscription;

    private NavHolder navHolder;

    private MapHandler mapHandler;
    private NavService navService;
    //用来标记是设置家或是公司的地址
    private UserAddressInfoImpl userAddressInfoImpl;

    @Override
    public void setView(IMVPView view) {
        navChoosePointInMapView = (INavChoosePointInMapView) view;
        super.setView(navChoosePointInMapView);

    }

    public NavChoosePointInMapPresenter(IMVPScheduler mvpScheduler, AbstractMapActivity mapActivity, MapHandler mapHandler) {
        super(mvpScheduler);
        this.mapActivity = mapActivity;
        this.mapHandler = mapHandler;
        res = mapActivity.getResources();
        navService = new NavService(mapActivity);
        userAddressInfoImpl = new UserAddressInfoImpl(mapActivity);
        requestMyLocate();
        registMyLocate();
    }

    /**
     * 注册广播以接受位置变更
     */
    private void registMyLocate() {
        locateSubscription = RxBus.getDefault().toObserverable(RxConstants.LOCATE, LocateStatus.class)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<LocateStatus>() {
                    @Override
                    public void call(LocateStatus locateStatus) {
                        requestMyLocate();
                    }
                });
        RxSubscriptions.add(locateSubscription);
    }

    @Override
    public void finish() {
        super.finish();
        RxSubscriptions.remove(locateSubscription);
    }

    /**
     * 主动请求位置变化信息
     */
    public void requestMyLocate() {
        navHolder = NavHolder.getInstance(mapActivity);
        LocateStatus locateStatus = navHolder.getLocateStatus();
        switch (locateStatus) {
            case LOCATED:
                if (navHolder.getMyLocation() != null) {
                    PoiItemInfo poiItemInfo = new PoiItemInfo();
                    poiItemInfo.setLatitude(navHolder.getMyLocation().getLatitude());
                    poiItemInfo.setLongitude(navHolder.getMyLocation().getLongitude());
                    mapHandler.showLocation(LocationType.POI, poiItemInfo);
                    mapHandler.geoCoderGps(navHolder.getMyLocation().getLatitude(), navHolder.getMyLocation().getLongitude(), LocationType.Custom);
                }
                break;
            case LOCATE_FAIL:
                break;
        }
        mapHandler.setCustomCoderGpsListener(this);
    }

    public void showMapPoint(PoiItemInfo poiItemInfo) {
        if (poiItemInfo != null && poiItemInfo.getLatitude() > 0) {
            mapHandler.showLocation(LocationType.POI, poiItemInfo);
            mapHandler.geoCoderGps(poiItemInfo.getLatitude(), poiItemInfo.getLongitude(), LocationType.Custom);
        } else {
            if (navChoosePointInMapView != null) {
                navChoosePointInMapView.onResponseError(new OnStarException("", res.getString(R.string.get_current_location_failed)));
            }
        }
    }

    @Override
    public void onSuccessCoder(PoiItemInfo poiItemInfo, LocationType locationType) {
        if (navChoosePointInMapView != null) {
            navChoosePointInMapView.showMarkerInfoView(poiItemInfo, locationType);
        }
    }

    @Override
    public void onErrorCoder(LocationType locationType, MapException mapExp) {
        if (navChoosePointInMapView != null) {
            navChoosePointInMapView.onResponseError(new OnStarException("", mapExp.getErrorString()));
        }
    }

    public void submit(String poiName, String poiAddress, final PoiItemInfo poiItemInfo, final MapChoosePoiType mapChoosePoiType) {
        if (CommonUtil.isNull(poiName) && CommonUtil.isNull(poiAddress)) {
            if (navChoosePointInMapView != null) {
                navChoosePointInMapView.onResponseError(new OnStarException("", res.getString(R.string.nav_no_map_point)));
            }
        } else {
            // 点击确定返回到设置回家地址页面
            if (mapChoosePoiType == MapChoosePoiType.HOME || mapChoosePoiType == MapChoosePoiType.COMPANY) {
                subscription = navService.dosaveHomeOrCompanyAddressInfo(poiItemInfo, mapChoosePoiType)
                        .subscribeOn(mvpScheduler.backgroundThread())
                        .observeOn(mvpScheduler.mainThread())
                        .subscribe(new Action1<String>() {
                            @Override
                            public void call(String s) {
                                if (mapChoosePoiType == MapChoosePoiType.HOME) {
                                    userAddressInfoImpl.saveUserAddressInfo(poiItemInfo, "1");
                                } else {
                                    userAddressInfoImpl.saveUserAddressInfo(poiItemInfo, "2");
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                //里面抛出的Error信息
                                if (navChoosePointInMapView != null) {
                                    navChoosePointInMapView.onResponseError((OnStarException) throwable);
                                }
                            }
                        });
            }
//            if (navChoosePointInMapView != null) {
//                if (mapChoosePoiType == MapChoosePoiType.COMPANY) {
//                    mapActivity.getNavDataHolder().setMapCompChoosePoi(poiItemInfo);
//                } else if (mapChoosePoiType == MapChoosePoiType.HOME) {
//                    mapActivity.getNavDataHolder().setMapHomeChoosePoi(poiItemInfo);
//                } else if (mapChoosePoiType == MapChoosePoiType.START_POI) {
//                    mapActivity.getNavDataHolder().setStartPoi(poiItemInfo);
//                } else if (mapChoosePoiType == MapChoosePoiType.END_POI) {
//                    mapActivity.getNavDataHolder().setEndPoi(poiItemInfo);
//                }   else if (mapChoosePoiType == MapChoosePoiType.SMART) {
//                    mapActivity.getNavDataHolder().setSmartPoi(poiItemInfo);
//                }
//                navChoosePointInMapView.onReponseSuccess(poiItemInfo);
//            }
            Intent intent = new Intent();
            SetAddressResult setAddressResult = new SetAddressResult();
            setAddressResult.mapChoosePoiType = mapChoosePoiType;
            setAddressResult.poiItemInfo = poiItemInfo;
            intent.putExtra("result",setAddressResult);
            mapActivity.setResult(1,intent);
            mapActivity.finish();
        }
    }
}